package com.manager.common.token;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import java.util.UUID;

public class RASUtils {

    private static PublicKey publicKey;
    private static PrivateKey privateKey;
    static {
        // 生成密钥对
       try {
           KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
           keyGen.initialize(1024);
           KeyPair keyPair = keyGen.generateKeyPair();
            publicKey = keyPair.getPublic();
            privateKey = keyPair.getPrivate();
       }catch (Exception e){
           e.printStackTrace();
       }
    }

    /**
     * 加密
     * */
    public static String encrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] dataByte =cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        String base64 = Base64.getEncoder().encodeToString(dataByte);
        base64 = base64.replaceAll("/","").replaceAll("\\\\","")
                .replaceAll("=","").replaceAll("\\+","");
        return base64;
    }

    /**
     * 解密
     * */
    public static String decrypt(String data ) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return new String(cipher.doFinal(Base64.getDecoder().decode(data)), StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception{
        // 加密和解密
        String data = UUID.randomUUID().toString();
        System.out.println(data);
        String result = RASUtils.encrypt(data);
        System.out.println(result);
        String decrypted = RASUtils.decrypt(result);
        System.out.println(decrypted); // 输出: Hello, RSA!
    }
}
